package com.dong.springboot.rabbitmq.work;

import com.dong.springboot.rabbitmq.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;

/**
 * @author: dong peng
 * @date: 2019/2/20 10:59
 * @description:
 */

public class RevWork2 {

    private static final String QUEUE_NAME = "queue1";

    public static void main(String[] args) throws IOException, InterruptedException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 同一时刻服务器只会发一条消息给消费者
        channel.basicQos(1);

        // 定义队列的消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        // 监听队列 false表示手动完成， true表示自动完成
        channel.basicConsume(QUEUE_NAME, true, consumer);

        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("接收器2接收到的消息： " + msg);

            Thread.sleep(1000);

            // 返回确认状态，注释表示使用自动确认
            // channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    }
}
